from .models import Prompt, AnalysisReport, WorkFlow
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.apps import apps
from django.urls import reverse
import json
from django.shortcuts import get_object_or_404, render
from .utils.data_tools import generate_markdown_table, extract_json_data
from .API import generate_completion
from .utils.processors import get_processor


def get_items(request, model_cls):
    try:
        items = model_cls.objects.filter(is_visible=True)
        data = [{'id': item.id, 'name': item.name,
                 'template': getattr(item, 'template', None),
                 'description': getattr(item, 'description', None)} for item in items]
        return JsonResponse(data, safe=False)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


# 特定的视图函数可以调用通用函数
def get_prompts(request):
    return get_items(request, Prompt)


def get_workflow(request):
    return get_items(request, WorkFlow)


@csrf_exempt
def ai_analysis(request):
    if request.method != 'POST':
        return JsonResponse({'error': 'Invalid request method'}, status=405)

    try:
        data = json.loads(request.body)
        messages = data.get('messages', '')
        if not messages:
            return JsonResponse({'error': 'No prompt provided'}, status=400)

        # messages = [
        #     {"role": "system", "content": "You are an assistant."},
        #     {"role": "user", "content": prompt}
        # ]
        print(messages)

        response_text = generate_completion(messages)
        print(response_text)
        response_json = {'response': response_text}

        # 从响应中提取信息（此函数需要自行实现）
        action_data = extract_json_data(response_text)

        if action_data and 'action' in action_data:
            action_type = action_data['action']
            processor = get_processor(action_type)
            result = processor.process(action_data)

            # 检查result是否包含错误信息，如果是字符串并且包含 "error"，则返回错误响应
            if isinstance(result, str) and "error" in result.lower():
                return JsonResponse({'error': result}, status=400)

            # 返回成功消息，包括生成的URL
            response_json['response'] += result

            if action_type == 'super_query':
                response_json['response'] = result

        return JsonResponse(response_json)

    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)


@csrf_exempt
def fetch_selected_items(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            app_label = data.get('app_label')
            model_name = data.get('model_name')
            item_ids = data.get('item_ids')

            if not app_label or not model_name or not isinstance(item_ids, list) or not item_ids:
                return JsonResponse({'error': 'Invalid data'}, status=400)

            ModelClass = apps.get_model(app_label, model_name)
            items = ModelClass.objects.filter(id__in=item_ids)
            if not items.exists():
                return JsonResponse({'error': 'No items found'}, status=404)

            markdown_string = generate_markdown_table(items)

            return JsonResponse({
                'items_data': markdown_string,
            }, json_dumps_params={'ensure_ascii': False})

        except LookupError:
            return JsonResponse({'error': 'Model not found'}, status=404)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': 'Invalid request method'}, status=405)


def report_detail(request, report_id):
    # 从数据库中获取特定ID的报告对象
    report = get_object_or_404(AnalysisReport, id=report_id)

    # 渲染模板并通过上下文传递报告数据
    return render(request, 'report_detail.html', {'report': report})


def review_report(request, report_id):
    try:
        # 获取指定 ID 的报告对象
        report = AnalysisReport.objects.get(id=report_id)
        # 将报告的审核状态设置为已审核
        report.is_reviewed = True
        # 保存报告对象的更改
        report.save()
        # 重定向到报告详情页面
        return HttpResponseRedirect(reverse('report_detail', args=[report_id]))
    except AnalysisReport.DoesNotExist:
        # 如果报告不存在，返回 404 错误响应
        return JsonResponse({'error': 'Report not found'}, status=404)
    except Exception as e:
        # 处理其他异常，返回错误信息和 500 状态码
        return JsonResponse({'error': str(e)}, status=500)


@csrf_exempt
def delete_report(request, report_id):
    try:
        # 获取指定 ID 的报告对象
        report = AnalysisReport.objects.get(id=report_id)
        # 删除报告对象
        report.delete()
        # 返回包含关闭页面 JavaScript 代码的响应
        return HttpResponse('<script>window.close();</script>')
    except AnalysisReport.DoesNotExist:
        # 如果报告不存在，返回 404 错误响应
        return JsonResponse({'error': 'Report not found'}, status=404)
    except Exception as e:
        # 处理其他异常，返回错误信息和 500 状态码
        return JsonResponse({'error': str(e)}, status=500)

